package com.cheejee.service.oss.impl;

import java.io.IOException;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.carry.common.file.FileName;
import com.cheejee.oss.dao.StorageMapper;
import com.cheejee.oss.entity.Storage;
import com.cheejee.oss.service.StorageService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

/**
 * @author CARRY
 * @Date 2020年11月6日上午12:27:31
 */
public class AliStorateServiceImpl implements StorageService {

	public static final Integer ALI_STORATE_TYPE = 2;

	private String endpoint;
	private String accessKeyId;
	private String accessKeySecret;
	private String bucketName;

	@Resource
	private StorageMapper mapper;

	public AliStorateServiceImpl(String endpoint, String accessKeyId, String accessKeySecret, String bucketName) {
		this.endpoint = endpoint;
		this.accessKeyId = accessKeyId;
		this.accessKeySecret = accessKeySecret;
		this.bucketName = bucketName;
	}

	@Override
	public PageInfo<Storage> query(Integer pageNum, Integer pageSize) {
		PageHelper.startPage(pageNum, pageSize);
		return new PageInfo<Storage>(mapper.selectByType(ALI_STORATE_TYPE));
	}

	@Override
	public String upload(MultipartFile file) throws IOException {
		OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
		try {
			String fileName = FileName.builder(file.getOriginalFilename());
			ossClient.putObject(bucketName, fileName, file.getInputStream());

			StringBuilder sb = new StringBuilder();
			sb.append("https://");
			sb.append(bucketName);
			sb.append(".");
			sb.append(endpoint);
			sb.append("/");
			sb.append(fileName);
			String url = sb.toString();

			Storage s = new Storage(null, fileName, url, file.getSize(), ALI_STORATE_TYPE, new Date());
			mapper.insertSelective(s);

			return url;

		} finally {
			showdown(ossClient);
		}

	}

	@Override
	@Transactional
	public void delete(Long[] id) {
		OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
		try {
			List<String> nl = mapper.selectKey(id);
			nl.forEach(i -> {
				ossClient.deleteObject(bucketName, i);
			});
			mapper.deleteMany(id);
			
		} finally {
			showdown(ossClient);
		}
	}

	private void showdown(OSS ossClient) {
		if (ossClient != null) {
			ossClient.shutdown();
		}
	}

}
